/**
 * Copyright (C) 2009 Infinity Learning Solutions.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package twitter.service;

import java.io.*;
import java.net.*;
import java.util.*;

import net.oauth.*;
import net.oauth.client.*;
import net.oauth.client.httpclient3.*;
import net.oauth.http.*;

import twitter.model.*;
import twitter.service.TwitterHttpCommand.*;

/**
 * This is the main class responsible for all OAuth communication with Twitter.
 * 
 * @author Troy Tolle - DigitalChalk.com
 * 
 */
public class TwitterOAuthService {
	private String requestTokenUrl;
	private String accessTokenUrl;
	private String authorizeUrl;

	/**
	 * 
	 */
	public TwitterOAuthService(String requestTokenUrl, String accessTokenUrl, String authorizeUrl) {
		this.requestTokenUrl = requestTokenUrl;
		this.accessTokenUrl = accessTokenUrl;
		this.authorizeUrl = authorizeUrl;
	}

	private OAuthAccessor newAccessor(TwitterConsumerCredentials credentials) {
		OAuthServiceProvider provider = new OAuthServiceProvider(requestTokenUrl, authorizeUrl, accessTokenUrl);
		OAuthConsumer consumer = new OAuthConsumer(null, credentials.getKey(), credentials.getSecret(), provider);
		return new OAuthAccessor(consumer);
	}

	private String asQueryString(Map<String, String> parameters) {
		StringBuffer buffer = new StringBuffer();
		if (null != parameters) {
			for (Iterator<Map.Entry<String, String>> iterator = parameters.entrySet().iterator(); iterator.hasNext();) {
				Map.Entry<String, String> entry = iterator.next();
				buffer.append(entry.getKey());
				buffer.append("=");
				try {
					buffer.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				if (iterator.hasNext()) {
					buffer.append("&");
				}
			}
		}
		return buffer.toString();
	}

	public TwitterTokenPair getRequestToken(TwitterConsumerCredentials credentials) throws TwitterOAuthException {
		TwitterTokenPair result = null;
		OAuthAccessor accessor = newAccessor(credentials);
		OAuthClient client = new OAuthClient(new HttpClient3());
		try {
			client.getRequestToken(accessor);
			// Build the token pair to return
			result = new TwitterTokenPair();
			result.setToken(accessor.requestToken);
			result.setTokenSecret(accessor.tokenSecret);
		} catch (Throwable t) {
			throw new TwitterOAuthException(t);
		}
		return result;
	}

	public String getAuthorizeUrl(String token, String callbackUrl, Map<String, String> callbackParameters) {
		Map<String, String> parameters = new HashMap<String, String>();
		parameters.put("oauth_token", token);
		if (null != callbackUrl) {
			parameters.put("oauth_callback", callbackUrl + "?" + asQueryString(callbackParameters));
		}
		return authorizeUrl + "?" + asQueryString(parameters);
	}

	public TwitterTokenPair getAccessToken(TwitterConsumerCredentials credentials, TwitterTokenPair requestTokenPair) throws TwitterOAuthException {
		TwitterTokenPair result = null;
		OAuthAccessor accessor = newAccessor(credentials);
		accessor.requestToken = requestTokenPair.getToken();
		accessor.tokenSecret = requestTokenPair.getTokenSecret();
		OAuthClient client = new OAuthClient(new HttpClient3());
		try {
			client.getAccessToken(accessor, HttpClient.GET, null);
			// Build the token pair to return
			result = new TwitterTokenPair();
			result.setToken(accessor.accessToken);
			result.setTokenSecret(accessor.tokenSecret);
		} catch (Throwable t) {
			throw new TwitterOAuthException(t);
		}
		return result;
	}
	
	public TwitterHttpResponse execute(TwitterHttpCommand command, HttpMethod method, TwitterTokenPair accessTokens, String url, Map<String, String> parameters) throws TwitterOAuthException {
		return command.execute(method, accessTokens, url, parameters);
	}

}
